package services

import (
	"context"
	"math"
	"wxapi/internal/svc"
	"wxapi/models"
)

// 定义地球半径，单位为千米
const earthRadius = 6371

// 将角度转换为弧度
func toRadians(degrees float64) float64 {
	return degrees * math.Pi / 180
}

func GetDistance(lat1, lon1, lat2, lon2 float64) float64 {
	// 将经纬度转换为弧度
	lat1Rad := toRadians(lat1)
	lon1Rad := toRadians(lon1)
	lat2Rad := toRadians(lat2)
	lon2Rad := toRadians(lon2)

	// 计算经纬度的差值
	dLat := lat2Rad - lat1Rad
	dLon := lon2Rad - lon1Rad

	// Haversine公式
	a := math.Pow(math.Sin(dLat/2), 2) + math.Cos(lat1Rad)*math.Cos(lat2Rad)*math.Pow(math.Sin(dLon/2), 2)
	c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))

	// 计算距离
	distance := earthRadius * c
	return math.Round(distance*100) / 100
}

func GetStoreExistsArea(ctx context.Context, svc *svc.ServiceContext, province, city string) ([]string, error) {
	area := make([]string, 0)

	if province == "" {
		list := make([]*models.Store, 0)

		svc.Mysql.Model(&models.Store{}).Select("province").Where("state = 100").Group("province").Find(&list)

		for _, v := range list {
			area = append(area, v.Province)
		}
	} else {
		if city != "" {
			list := make([]*models.Store, 0)

			svc.Mysql.Model(&models.Store{}).Select("area").Where("state = 100 AND province = ? AND city = ?", province, city).Group("area").Find(&list)

			for _, v := range list {
				area = append(area, v.Area)
			}
		} else {
			list := make([]*models.Store, 0)

			svc.Mysql.Model(&models.Store{}).Select("city").Where("state = 100 AND province = ?", province).Group("city").Find(&list)

			for _, v := range list {
				area = append(area, v.City)
			}
		}
	}

	return area, nil
}
